package com.example.human_resource_management.controller;

import com.example.human_resource_management.common.ResponseData;
import com.example.human_resource_management.entry.po.Filein;
import com.example.human_resource_management.entry.vo.UploadResultVo;
import com.example.human_resource_management.service.FileinService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

/**
 * 通用控制器
 */
@RestController
@RequestMapping("/api/common")
public class CommonController {

    @Resource
    private MinioClient minioClient;
    @Autowired
    private FileinService fileinService;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

    // 文件上传
    @PostMapping("uploadminio")
    public ResponseData<UploadResultVo> uploadFile(@RequestParam("file") MultipartFile file) {
        UploadResultVo uploadResultVo = new UploadResultVo();
        if (file.isEmpty()) {
            return ResponseData.warn("Error: File is empty");
        }
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;
            // 上传文件到 MinIO
            try (InputStream inputStream = file.getInputStream()) {
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucketName)
                                .object(uniqueFileName)
                                .stream(inputStream, file.getSize(), -1)
                                .contentType(file.getContentType())
                                .build()
                );
            }

            // 构建文件访问 URL
            String fileUrl = String.format("%s/%s/%s", endpoint, bucketName, uniqueFileName);
            uploadResultVo.setUrl(fileUrl);
            uploadResultVo.setBucket(bucketName);
            uploadResultVo.setFileName(originalFilename);

            String[] parts = fileUrl.split("/");
            String fileName = parts[parts.length - 1];

            Filein filein = new Filein();
            filein.setName(originalFilename);
            filein.setPath(fileUrl);
            filein.setSize(file.getSize());
            filein.setType(fileName.substring(fileName.lastIndexOf(".") + 1));
            filein.setUploadTime(new Date());
            fileinService.save(filein);
        } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            return ResponseData.warn("Error uploading file: " + e.getMessage());
        }
        return ResponseData.ok(uploadResultVo);
    }

    // 文件删除
    @DeleteMapping("deleteminio/{fileId}")
    public ResponseData<String> deleteFile(@PathVariable Long fileId) {
        if (fileId == null || fileId <= 0) {
            return ResponseData.warn("Error: Invalid file ID");
        }

        try {
            // 1. 从数据库查询文件信息
            Filein filein = fileinService.getById(fileId);
            if (filein == null) {
                return ResponseData.warn("Error: File not found");
            }

            // 2. 从文件URL中提取文件名和桶名
            String fileUrl = filein.getPath();
            String[] parts = fileUrl.split("/");
            if (parts.length < 3) {
                return ResponseData.warn("Error: Invalid file URL format");
            }

            String fileName = parts[parts.length - 1];

            // 3. 从MinIO删除文件
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );

            // 4. 从数据库删除记录
            fileinService.removeById(fileId);

            return ResponseData.ok("File deleted successfully");
        } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            return ResponseData.warn("Error deleting file: " + e.getMessage());
        }
    }
}